package com.example.netty;


import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;

/**
 * Created by dingshuo on 2017/7/6.
 */
public class UploadClient {
    public static void main(String[] args) throws Exception{
        UploadClient client=new UploadClient();
        client.connect();
    }


    public void connect(){
        EventLoopGroup group=new NioEventLoopGroup();
        try{
            Bootstrap b=new Bootstrap();
            b.group(group).channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY,true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new ChannelInboundHandlerAdapter(){
                                @Override
                                public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                    ByteBuf msg;
                                    InputStream in = new FileInputStream("D:\\data\\aa\\a1.mp4");
                                    ByteArrayOutputStream out = new ByteArrayOutputStream();
                                    byte[] buffer = new byte[1024 * 100];
                                    int n = 0;
                                    while ((n = in.read(buffer)) != -1) {
                                        msg= Unpooled.buffer(buffer.length);
                                        //这里读取到多少，就发送多少，是为了防止最后一次读取没法满填充buffer，
                                        //导致将buffer中的处于尾部的上一次遗留数据也发送走
                                        msg.writeBytes(buffer,0,n);
                                        ctx.writeAndFlush(msg);
                                        msg.clear();
                                    }
                                    System.out.println(n);

                                }
                            });
                        }
                    });

            ChannelFuture f=b.connect("127.0.0.1",20000).sync();
            f.channel().closeFuture().sync();
        }catch (Exception e){

        }finally {
            group.shutdownGracefully();
        }
    }
}

